<?php
/**
 * @deprecated - v2.3 已经取消淘宝数据抓取功能了
 *
 * Description: 淘宝商品查询
 * Author: hezhizheng
 * Date: 2018/5/8
 * Time: 9:05
 * Created by Created by Panxsoft.
 */

namespace App\Services\TaoBao;

use App\Exceptions\ApiErrCode;
use App\Exceptions\ApiException;
use App\Http\Controllers\Debug\DebugController;
use App\Services\Utils\CurlApi;
use QL\Ext\PhantomJs;
use QL\QueryList;
use Tests\TaoBao\ItemDetailTest;

class ItemDetailService
{
    protected $try_count = 0;

    /**
     * 通过淘宝商品 url 获取商品 id
     *
     * @test
     * @see ItemDetailTest::test_getTaoBaoGoodsIdForUrl()
     *
     * @param string $url
     * @return mixed|string
     */
    public function getTaoBaoGoodsIdForUrl(string $url): string
    {
        // https://item.taobao.com/item.htm?id=565872973022&ali_trackid=2:mm_122269968_22140934_73734727:1525742025_233_2002879073&spm=a21bo.7925826.192013.1.497a4c0dB0gHWP
        $goods_id = @explode('&', explode('?id=', $url)[1])[0];

        return $goods_id;
    }

    public function getTaoBaoItemDetail()
    {

    }

    public function taoBaoItemDetail()
    {

    }


    /**
     * 先调用 node 写的爬虫获取 html 代码，在通过 queryList 解析 html
     *
     * @param string $url
     *
     * @return array|null
     * @throws ApiException
     */
    public function crawlerGetItemDetailUseNode(string $url): ? array
    {

        try {
            $query_lists = $this->queryListHtml($url);

            $query_lists[0]['pic'] = 'https:' . trim($query_lists[0]['pic'], 'https:');

        } catch (\Exception $exception) {
            throw New ApiException(
                ApiErrCode::TAOBAO_CRAWLER_FAIL,
                trans('service.taobao_message') . $exception->getMessage()
            );
        };


        return $query_lists[0] ?? null;

    }

    /**
     * 执行爬虫操作、解析DOM
     *
     * @param $url
     * @return array
     */
    private function queryListHtml($url)
    {
        /**
         * 请求node写的爬虫
         */
        $html = CurlApi::curl(config('pkx.node_crawler_url'), ['url' => $url], 1);

        $this->try_count++;
        $query_lists = QueryList::html($html)
            ->rules($this->getQueryListRules($url))
            ->query()
            ->getData()
            ->all();

//        if (count($query_lists[0]) < 5 && $this->try_count < 4) { // 如果或取的参数信息不全,继续爬虫尝试3次。
//            logger('尝试第：' . $this->try_count . ' 次' . '（' . $url . '）');
//            $query_lists = $this->queryListHtml($url);
//        }

        return $query_lists;
    }

    /**
     * @deprecated - 请使用 node 的接口
     *
     * 通过queryList爬虫获取淘宝、天猫商品信息
     *
     * @test
     * @see DebugController::testQueryList()
     *
     * @param string $url
     * @return mixed|array
     */
    public function crawlerGetItemDetail(string $url): ? array
    {
        /**
         * @link https://doc.querylist.cc/
         */
        $ql = QueryList::getInstance();

        $ql->use(PhantomJs::class, config('pkx.phantom_js_path'));

        /**
         * 忽略 ServiceContainer.php load() 错误
         * docker 中使用会报错
         * @link https://doc.querylist.cc/site/index/doc/40
         */
        $html = @$ql->browser($url)->getHtml();

        $query_lists = QueryList::html($html)
            ->rules($this->getQueryListRules($url))
            ->query()
            ->getData(function ($item) {
                $item['pic'] = 'https:' . $item['pic'];
                return $item;
            })
            ->all();

        return $query_lists[0] ?? null;

    }

    /**
     * @param $url
     * @return array
     */
    private function getQueryListRules($url): array
    {
        if (str_contains($url, 'taobao.com')) {
            return $this->taoBaoRules();
        } else {
            return $this->tianMaoRules();
        }
    }

    /**
     * @return array
     */
    private function taoBaoRules(): array
    {
        return [
            'title'       => ['.tb-main-title', 'html'],
            'pic'         => ['#J_ImgBooth', 'src'],
            'promo_price' => ['#J_PromoHd .tb-rmb-num', 'html'],
            'price'       => ['#J_StrPriceModBox .tb-rmb-num', 'html'],
            'sell_count'  => ['#J_SellCounter', 'html'], // 淘宝是交易量
        ];
    }

    /**
     * @return array
     */
    private function tianMaoRules(): array
    {
        return [
            'title'       => ['title', 'html'],
            'pic'         => ['#J_ImgBooth', 'src'],
            'promo_price' => ['#J_PromoPrice .tm-price', 'html'],
            'price'       => ['#J_StrPriceModBox .tm-price', 'html'],
            'sell_count'  => ['.tm-ind-sellCount>.tm-indcon>.tm-count', 'html'], // 天猫是月销量
        ];
    }


}